<template>
  <div>
    <el-page-header @back="goBack" content="教室预约">
      <template slot="title">
        <el-link type="primary">返回教室详情</el-link>
      </template>
    </el-page-header>

    <el-steps :active="active" align-center finish-status="success">
      <el-step title="教室信息"></el-step>
      <el-step title="个人信息"></el-step>
      <el-step title="核对信息"></el-step>
    </el-steps>
    <!-- 中间内容 -->
    <el-card>
      <el-form
        label-position="right"
        label-width="110px"
        :rules="rules"
        ref="reviewForm"
        :model="reviewForm"
      >
        <!-- 第一部分 -->
        <div v-show="active==0" class="section-one">
          <el-form-item class="classroomName" label="教室名:">
            <el-tag type="danger" effect="dark" v-text="reviewForm.classroomName"></el-tag>
          </el-form-item>

          <el-form-item class="building" label="所在教学楼:">
            <el-tag type="success" effect="dark">教学楼 {{reviewForm.building}}</el-tag>
          </el-form-item>

          <el-form-item class="classroomType" label="教室类型:">
            <el-tag effect="dark" v-show="reviewForm.type==0">小型</el-tag>
            <el-tag effect="dark" v-show="reviewForm.type==1">中型</el-tag>
            <el-tag effect="dark" v-show="reviewForm.type==2">大型</el-tag>
          </el-form-item>

          <el-form-item label="开始时间:" prop="beginTime">
            <el-col :span="11">
              <el-date-picker
                prefix-icon="el-icon-right"
                type="datetime"
                :picker-options="pickerOptionsStart"
                placeholder="选择开始时间:"
                v-model="reviewForm.beginTime"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                @blur="getTotalCount"
                default-time="8:00:00"
              ></el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="结束时间:" prop="endTime">
            <el-col :span="11">
              <el-date-picker
                prefix-icon="el-icon-back"
                :picker-options="pickerOptionsEnd"
                type="datetime"
                placeholder="结束时间:"
                v-model="reviewForm.endTime"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                @blur="getTotalCount"
                default-time="10:00:00"
              ></el-date-picker>
            </el-col>
          </el-form-item>

          <el-form-item class="reason" label="申请理由:" prop="usedReason">
            <div class="edit_container">
              <quill-editor
                v-model="reviewForm.usedReason"
                ref="myQuillEditor"
                :options="editorOption"
                @blur="onEditorBlur($event)"
                @focus="onEditorFocus($event)"
                @change="onEditorChange($event)"
              ></quill-editor>
            </div>
          </el-form-item>
        </div>

        <!-- 第二部分 -->
        <div v-show="active==1">
          <div class="section-two">
            <el-form-item prop="cardNum" class="section-two-item" label="学号:">
              <el-input clearable v-model="reviewForm.cardNum"></el-input>
            </el-form-item>
            <el-form-item prop="applicant" class="section-two-item" label="申请人姓名:">
              <el-input clearable v-model="reviewForm.applicant"></el-input>
            </el-form-item>

            <el-form-item prop="applicantPhone" class="section-two-item" label="手机号:">
              <el-input clearable v-model="reviewForm.applicantPhone"></el-input>
            </el-form-item>

            <el-form-item class="section-two-item" label="邮箱:" prop="applicantEmail">
              <el-input clearable v-model="reviewForm.applicantEmail"></el-input>
            </el-form-item>
            <el-form-item prop="reviewerId" class="section-two-item" label="选择审批人:">
              <el-select
                clearable
                @change="currentFocus"
                v-model="reviewForm.reviewerId"
                placeholder="选择审批人"
              >
                <el-option
                  v-for="item in reviewerOptions"
                  :key="item.mgId"
                  :label="item.realName"
                  :value="item.mgId"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>

        <!-- 信息确认部分 -->
        <div class="section-threee" v-show="active==2">
          <div>
            <!-- 左边 -->
            <el-col :span="12">
              <el-timeline>
                <el-timeline-item
                  size="large"
                  :timestamp="reviewForm.classroomName"
                  type="primary"
                >教室名</el-timeline-item>
              </el-timeline>
              <el-timeline>
                <el-timeline-item type="primary" :timestamp="reviewForm.building">教学楼</el-timeline-item>
              </el-timeline>
              <el-timeline>
                <el-timeline-item type="primary" :timestamp="reviewForm.beginTime">开始时间</el-timeline-item>
              </el-timeline>
              <el-timeline>
                <el-timeline-item type="primary" :timestamp="reviewForm.endTime">结束时间</el-timeline-item>
              </el-timeline>
              <el-timeline>
                <el-timeline-item v-if="reviewForm.type==0" type="primary" timestamp="小型教室">类型</el-timeline-item>
                <el-timeline-item v-else-if="reviewForm.type==1" type="primary" timestamp="中型教室">类型</el-timeline-item>
                <el-timeline-item v-else="reviewForm.type==2" type="primary" timestamp="大型教室">类型</el-timeline-item>
              </el-timeline>
            </el-col>

            <!-- 左边 -->
            <el-col :span="12">
              <el-timeline>
                <el-timeline-item type="danger" :timestamp="reviewForm.content">座位数</el-timeline-item>
              </el-timeline>

              <el-timeline>
                <el-timeline-item type="danger" :timestamp="reviewForm.applicant">申请人</el-timeline-item>
              </el-timeline>
              <el-timeline>
                <el-timeline-item type="danger" :timestamp="reviewForm.applicantEmail">邮箱</el-timeline-item>
              </el-timeline>
              <el-timeline>
                <el-timeline-item type="danger" :timestamp="reviewForm.applicantPhone">手机号</el-timeline-item>
              </el-timeline>
              <el-timeline>
                <el-timeline-item type="danger" :timestamp="managerName">审核人</el-timeline-item>
              </el-timeline>
            </el-col>

            <el-col :span="24">
              <el-divider content-position="center">申请理由</el-divider>
              <el-card class="applyReason" v-html="reviewForm.usedReason"></el-card>

              <el-divider></el-divider>
            </el-col>
          </div>
          <el-form-item>
            <el-button
              :disabled="disabledSubmit"
              class="onSubmit"
              type="primary"
              @click="onSubmit('reviewForm')"
            >确认提交</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>
    <div class="operation">
      <el-button type="primary" :disabled="disableBack" style="margin-top: 12px;" @click="back">上一步</el-button>
      <el-button type="success" :disabled="disableNext" style="margin-top: 12px;" @click="next">下一步</el-button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    // 校验手机号
    var validatorPhone = function(rule, value, callback) {
      if (value === "") {
        callback(new Error("手机号不能为空"));
      } else if (!/^1\d{10}$/.test(value)) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };

    return {
      active: 0,
      backDisabled: false,
      forwordDisabled: false,
      reviewForm: {
        cardNum: "",
        reviewerId: "",
        classroomName: "",
        building: "",
        beginTime: "",
        endTime: "",
        type: "",
        content: "",
        applicant: "",
        applicantEmail: "",
        applicantPhone: "",
        usedReason: "",
        interval: 1
      },
      reviewerOptions: [
        {
          mgId: "",
          realName: ""
        }
      ],
      disableBack: false,
      disableNext: false,
      managerName: "",
      rules: {
        usedReason: [
          { required: true, message: "申请理由不能为空", trigger: "blur" },
          { min: 5, message: "字数至少5个字", trigger: "blur" }
        ],
        cardNum: [
          { required: true, message: "学号不能为空", trigger: "blur" },
          { min: 9, max: 9, message: "学号是9位", trigger: "change" }
        ],
        applicant: [
          {
            type: "string",
            required: true,
            message: "申请人不能为空",
            trigger: "blur"
          }
        ],
        applicantPhone: [
          {
            validator: validatorPhone,
            trigger: "change"
          }
        ],
        applicantEmail: [
          {
            type: "email",
            required: true,
            message: "邮箱格式不对",
            trigger: "change"
          }
        ],
        reviewerId: [
          { required: true, message: "请选择审核人", trigger: "blur" }
        ],
        beginTime: [
          {
            required: true,
            message: "开始时间不能为空",
            trigger: "blur"
          }
        ],
        endTime: [
          {
            required: true,
            message: "结束时间不能为空",
            trigger: "blur"
          }
        ]
      },
      // 提交按钮
      disabledSubmit: false,
      pickerOptionsStart: {
        disabledDate: time => {
          if (this.reviewForm.endTime) {
            return time.getTime() > new Date(this.reviewForm.endTime).getTime();
          }
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            }
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            }
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            }
          }
        ]
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          if (this.reviewForm.beginTime) {
            return (
              time.getTime() <
              new Date(this.reviewForm.beginTime).getTime() - 86400000
            );
          }
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            }
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            }
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            }
          }
        ]
      },
      content: "",
      editorOption: {
        placeholder: "请输入",
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
            ["blockquote", "code-block"], //引用，代码块
            [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
            [{ list: "ordered" }, { list: "bullet" }], //列表
            [{ indent: "-1" }, { indent: "+1" }], // 缩进
            [{ size: ["small", false, "large", "huge"] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6, false] }], //几级标题
            [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            [{ align: [] }], //对齐方式
            ["clean"] //清除字体样式
          ]
        }
      }
    };
  },

  methods: {
    currentFocus() {
      this.getManagerNameById();
    },
    next() {
      if (this.active != 2) {
        this.active++;
        this.disableBack = false;
      } else if (this.active == 2) {
        this.disableNext = true;
        this.disableBack = false;
        return this.$message.warning("不能再往前了");
      }
    },
    back() {
      if (this.active != 0) {
        this.active--;
        this.disableNext = false;
      } else if (this.active == 0) {
        this.disableBack = true;
        this.disableNext = false;
        return this.$message.warning("不能再往前了");
      }
    },
    goBack() {
      let name = this.$route.query.name;
      this.$router.push("/classroomDetails?name=" + name);
    },

    onSubmit(formName) {
      // 确认提交
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$http
            .post("apply/saveApplyReport", this.reviewForm)
            .then(resp => {
              let { code, msg } = resp.data;
              if (code == 1) {
                this.$notify({
                  title: "提交成功",
                  message: "消息来了",
                  type: "success"
                });
                this.disabledSubmit = true;
                return this.$router.push("/applyHistory");
              }
              return this.$notify({
                title: msg,
                message: "消息来了",
                type: "error"
              });
            })
            .catch(resp => {});
        } else {
          return this.$message.warning("检查一下吧，数据好像不完整！");
        }
      });
    },
    getClassDetails(name) {
      this.$http
        .get(`/classroom/noAuthorize/queryAvailableClassroom/${name}`)
        .then(resp => {
          let { code, msg, data } = resp.data;
          if (code == 1) {
            this.reviewForm.building = data.classroom.building;
            this.reviewForm.content = data.classroom.content.toString();
          }
        })
        .catch(resp => {});
    },
    getUserLoginUserInfo() {
      this.$http
        .get("/user/userId/")
        .then(resp => {
          let { code, msg, data } = resp.data;
          if (code == 1) {
            let user = data.user;
            this.reviewForm.applicant = user.username;
            this.reviewForm.applicantPhone = user.userTel;
            this.reviewForm.applicantEmail = user.userEmail;
            this.reviewForm.cardNum = user.cardNum;
          }
        })
        .catch(resp => {});
    },
    getManagerInfoAll() {
      this.$http
        .get("/manager/noAuthorize/managerInfo/all/")
        .then(resp => {
          let { code, msg, data } = resp.data;
          if (code == 1) {
            this.reviewerOptions = data.managerList;
          }
        })
        .catch(resp => {});
    },
    getManagerNameById() {
      this.$http
        .get("/manager/noAuthorize/id/", {
          params: {
            reviewerId: this.reviewForm.reviewerId
          }
        })
        .then(resp => {
          let { code, msg, data } = resp.data;

          if (code == 1) {
            this.managerName = data.manager.realName;
          }
        })
        .catch(resp => {});
    },
    getTotalCount() {
      this.queryReviewHistory();
      this.queryCourseHistory();
    },
    queryReviewHistory() {
      let name = this.$route.query.name;
      this.$http
        .get("/apply/noAuthorize/history", {
          params: {
            beginTime: this.reviewForm.beginTime,
            endTime: this.reviewForm.endTime,
            name: this.reviewForm.classroomName
          }
        })
        .then(resp => {
          let { code, msg } = resp.data;
          if (code == 404) {
            // 不存在记录，可以使用
            this.disabledSubmit = false;
            return;
          } else if (code == 400) {
            // 开始时间大于结束时间，不可使用
            this.$message.info(msg);
            this.disabledSubmit = true;
            return;
          } else if (code == 1) {
            // 存在记录，不可用使用
            let { total } = resp.data.data.pageResult;
            this.$message.warning(
              "当前时间段与 " +
                total +
                " 条 预定信息 安排冲突了，请选择合适时间段哦"
            );
            this.disabledSubmit = true;
            return;
          }
          // 其他情况(code=0)
          this.$message.warning("服务器出错" + msg);
          this.disabledSubmit = true;
        })
        .catch(resp => {});
    },
    queryCourseHistory() {
      let name = this.$route.query.name;
      this.$http
        .get("/course/noAuthorize/history", {
          params: {
            beginTime: this.reviewForm.beginTime,
            endTime: this.reviewForm.endTime,
            name: this.reviewForm.classroomName
          }
        })
        .then(resp => {
          let { code, msg } = resp.data;
          if (code == 1) {
            let { total } = resp.data.data.pageResult;
            this.$message.warning(
              "当前时间段与 " + total + "条 课程安排 冲突了，请选择合适时间段哦"
            );
            this.disabledSubmit = true;
            return;
          } else if (code == 400) {
            this.$message.info(msg);
            this.disabledSubmit = true;
            return;
          } else if (code == 404) {
            this.disabledSubmit = false;
            return;
          }
          this.$message.warning("服务器出错" + msg);
          this.disabledSubmit = true;
        })
        .catch(resp => {});
    },
    onEditorReady(editor) {
      // 准备编辑器
    },
    onEditorBlur() {}, // 失去焦点事件
    onEditorFocus() {}, // 获得焦点事件
    onEditorChange() {} // 内容改变事
  },
  created() {
    let name = this.$route.query.name;
    this.reviewForm.classroomName = name;
    this.reviewForm.beginTime = this.$route.query.beginTime;
    this.reviewForm.endTime = this.$route.query.endTime;
    this.reviewForm.type = this.$route.query.type;
    if (name) {
      this.getClassDetails(name);
    }
    this.getUserLoginUserInfo();
    this.getManagerInfoAll();
  },

  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill;
    }
  }
};
</script>

<style scoped lang='less'>
.el-steps {
  margin-top: 10px;
  margin-bottom: 10px;
}
.el-card {
  margin-left: 75px;

  width: 800px;
}
.operation {
  margin-top: 5px;
  margin-left: 380px;
}
.el-form {
  margin-right: 60px;
  margin-top: 30px;
  margin-left: 60px;

  .classroomName {
    width: 250px;
  }
  .building {
    width: 250px;
  }
  .classroomType {
    width: 250px;
  }

  .reviewer {
    width: 250px;
  }
  .section-two {
    margin-top: 20px;
    margin-left: 120px;
    .section-two-item {
      width: 400px;
      .el-select {
        width: 290px;
      }
    }
  }
  .onSubmit {
    margin-left: 162px;
  }
}
.el-timeline {
  margin-left: 80px;
}
.el-page-header {
  margin-top: 10px;
  margin-left: 10px;
}
.section-one {
  margin-left: 0px;
}
.el-page-header {
  margin-top: 20px;
}
.applyReason {
  text-align: center;
  width: 500px;
}
</style>